from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView, ListAPIView
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from goods.models import SKU
from orders.models import OrderGoods
from orders.serializers import OrderPlaceSerializer, OrderCommitSerializer, SkuCommentSerializer, GoodCommentSerializer
from decimal import Decimal
from rest_framework.generics import CreateAPIView


class OrderPlaceView(GenericAPIView):
    serializer_class = OrderPlaceSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 1,获取redis中需要结算的商品
        user = request.user
        redis_conn = get_redis_connection("cart")
        cart_dict = redis_conn.hgetall("cart_%s" % user.id)
        cart_selected_list = redis_conn.smembers("cart_selected_%s"%user.id)

        # 2,拼接数据
        sku_list = []
        for sku_id  in cart_selected_list:
            sku = SKU.objects.get(id=sku_id)
            sku.count = int(cart_dict[sku_id])
            sku_list.append(sku)

        # 3,获取序列化器
        serializer = self.get_serializer(instance=sku_list,many=True)

        # 4,返回响应
        contenxt = {
            "skus":serializer.data,
            "freight":Decimal(10.0)
        }
        return Response(contenxt)


class OrderCommitView(CreateAPIView):
    serializer_class = OrderCommitSerializer
    permission_classes = [IsAuthenticated]


class OrderSkuComment(GenericAPIView):
    serializer_class = SkuCommentSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        "获取需要评价的订单商品"
        queryset = OrderGoods.objects.filter(order_id = order_id, is_commented=False)

        serializer = self.get_serializer(instance=queryset, many=True)
        print(serializer.data)
        return Response(serializer.data)

    def post(self, request, order_id):
        """在订单商品中创建商品的评论"""

        # 获取参数
        dict_data = request.data
        # order: this.order_id,
        # sku_id: sku.sku.id,
        # comment: sku.comment,
        # score: sku.final_score,
        # is_anonymous: sku.is_anonymous,

        # 创建序列化器
        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(status=status.HTTP_201_CREATED)


class ShowSkuComment(ListAPIView):
    """获取商品评论信息"""
    serializer_class = GoodCommentSerializer

    def get_queryset(self):
        return OrderGoods.objects.filter(sku_id=self
                                         .kwargs.get('sku_id'),is_commented=True)



